package org.jeecg.modules.middle.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.cmbCloudDirectLink.utils.GENKey;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.LimitSubmit;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.*;
import org.jeecg.modules.manage.vo.CaishuiBusinessPage;
import org.jeecg.modules.middle.business.service.*;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


/**
 * @Description: 商户基本信息表[中台]
 * @Author: yfkj
 * @Date:   2023-02-07
 * @Version: V1.0
 */
@Api(tags="商户基本信息表[中台]")
@RestController
@RequestMapping("/business/caishuiBusiness")
@Slf4j
public class CaishuiBusinessController {
	@Autowired
	private ICaishuiBusinessService iCaishuiBusinessService;
	@Autowired
	private ICaishuiBusinessUserService caishuiBusinessUserService;
	@Autowired
	private ICaishuiBusinessBankService caishuiBusinessBankService;
	@Autowired
	private ICaishuiMiddleUserService iCaishuiMiddleUserService;
	@Autowired
	private ICaishuiChannelBindingService iCaishuiChannelBindingService;
	@Autowired
	private ICaishuiServiceCompanyService iCaishuiServiceCompanyService;
	@Resource
	private ICaishuiCompanySetService iCaishuiCompanySetService;

	//========================================普通商户基本信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusiness
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[中台]-分页列表查询", notes="普通商户基本信息[中台]-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<IPage<CaishuiBusiness>> queryPageList(CaishuiBusiness caishuiBusiness,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		//当前登录用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		String parentId = caishuiBusiness.getPid();
		if (oConvertUtils.isEmpty(parentId)) {
			parentId = "0";
		}
		caishuiBusiness.setPid(null);
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
		queryWrapper.lambda().eq(CaishuiBusiness::getType,1);//普通商户
		if(loginUser.getUserType()==2 && loginUser.getMiddleOptAuth()==2){//中台渠道角色登录则只能查看自己的商户
			//查询渠道商户
			queryWrapper.lambda().eq(CaishuiBusiness::getChannelBusinessId,loginUser.getChannelBusinessId());
			if(loginUser.getMiddleUserType()==2){//员工
				queryWrapper.lambda().eq(CaishuiBusiness::getUserId,loginUser.getId());
			}
		}
		// 使用 eq 防止模糊查询
		queryWrapper.eq("pid", parentId);
		Page<CaishuiBusiness> page = new Page<CaishuiBusiness>(pageNo, pageSize);
		IPage<CaishuiBusiness> pageList = iCaishuiBusinessService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 【vue3专用】加载节点的子数据
	 *
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
		Result<List<SelectTreeModel>> result = new Result<>();
		try {
			List<SelectTreeModel> ls = iCaishuiBusinessService.queryListByPid(pid);
			result.setResult(ls);
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 【vue3专用】加载一级节点/如果是同步 则所有数据
	 *
	 * @param async
	 * @param pcode
	 * @return
	 */
	@RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		Result<List<SelectTreeModel>> result = new Result<>();
		try {
			List<SelectTreeModel> ls = iCaishuiBusinessService.queryListByCode(pcode);
			if (!async) {
				loadAllChildren(ls);
			}
			result.setResult(ls);
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 【vue3专用】递归求子节点 同步加载用到
	 *
	 * @param ls
	 */
	private void loadAllChildren(List<SelectTreeModel> ls) {
		for (SelectTreeModel tsm : ls) {
			List<SelectTreeModel> temp = iCaishuiBusinessService.queryListByPid(tsm.getKey());
			if (temp != null && temp.size() > 0) {
				tsm.setChildren(temp);
				loadAllChildren(temp);
			}
		}
	}

	/**
	 * 获取子数据
	 * @param caishuiBusiness
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[中台]-获取子数据", notes="普通商户基本信息[中台]-获取子数据")
	@GetMapping(value = "/childList")
	public Result<IPage<CaishuiBusiness>> queryPageList(CaishuiBusiness caishuiBusiness,HttpServletRequest req) {
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
		List<CaishuiBusiness> list = iCaishuiBusinessService.list(queryWrapper);
		IPage<CaishuiBusiness> pageList = new Page<>(1, 10, list.size());
		pageList.setRecords(list);
		return Result.OK(pageList);
	}

	/**
	 * 批量查询子节点
	 * @param parentIds 父ID（多个采用半角逗号分割）
	 * @return 返回 IPage
	 * @param parentIds
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[中台]-批量获取子数据", notes="普通商户基本信息[中台]-批量获取子数据")
	@GetMapping("/getChildListBatch")
	public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
		try {
			QueryWrapper<CaishuiBusiness> queryWrapper = new QueryWrapper<>();
			List<String> parentIdList = Arrays.asList(parentIds.split(","));
			queryWrapper.in("pid", parentIdList);
			List<CaishuiBusiness> list = iCaishuiBusinessService.list(queryWrapper);
			IPage<CaishuiBusiness> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
			return Result.OK(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("批量查询子节点失败：" + e.getMessage());
		}
	}

	/**
	 *   添加
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-添加", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-添加", notes="普通商户基本信息[中台]-添加")
	@PostMapping(value = "/add")
	@LimitSubmit(key = "middle:business:add:%tId")
	public Result<String> add(@RequestBody CaishuiBusiness caishuiBusiness) {
		caishuiBusiness.setType(1);
		iCaishuiBusinessService.addCaishuiBusiness(caishuiBusiness);
		return Result.OK("添加成功！",caishuiBusiness.getId());
	}

	/**
	 *  编辑
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-编辑", dataType = 2, terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-编辑", notes="普通商户基本信息[中台]-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@LimitSubmit(key = "middle:business:edit:%tId", spelKey = "#caishuiBusiness.id")
	public Result<String> edit(@RequestBody CaishuiBusiness caishuiBusiness) {
		iCaishuiBusinessService.updateCaishuiBusiness(caishuiBusiness);
		return Result.OK("编辑成功!",caishuiBusiness.getId());
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-通过id删除", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-通过id删除", notes="普通商户基本信息[中台]-通过id删除")
	@DeleteMapping(value = "/delete")
	@LimitSubmit(key = "middle:business:delete:%tId", spelKey = "#id")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		iCaishuiBusinessService.deleteCaishuiBusiness(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param caishuiBusiness
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, CaishuiBusiness caishuiBusiness) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, request.getParameterMap());
		//当前登录用户
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(sysUser.getUserType()==2 && sysUser.getMiddleOptAuth()==2){//中台渠道角色
			caishuiBusiness.setChannelBusinessId(sysUser.getChannelBusinessId());
			if(sysUser.getMiddleUserType()==2){//员工
				caishuiBusiness.setUserId(sysUser.getId());
			}
		}
		//配置选中数据查询条件
		String selections = request.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		//Step.2 获取导出数据
		List<CaishuiBusiness> caishuiBusinessList = iCaishuiBusinessService.list(queryWrapper);

		// Step.3 组装pageList
		List<CaishuiBusinessPage> pageList = new ArrayList<CaishuiBusinessPage>();
		for (CaishuiBusiness main : caishuiBusinessList) {
			CaishuiBusinessPage vo = new CaishuiBusinessPage();
			BeanUtils.copyProperties(main, vo);
			List<CaishuiBusinessUser> caishuiBusinessUserList = caishuiBusinessUserService.selectByMainId(main.getId());
			vo.setCaishuiBusinessUserList(caishuiBusinessUserList);
			List<CaishuiBusinessBank> caishuiBusinessBankList = caishuiBusinessBankService.selectByMainId(main.getId());
			vo.setCaishuiBusinessBankList(caishuiBusinessBankList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "商户信息列表");
		mv.addObject(NormalExcelConstants.CLASS, CaishuiBusinessPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商户信息数据", "导出人："+sysUser.getRealname(), "商户信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}
	//========================================普通商户基本信息=========================================

    //========================================普通商户银行账户=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusinessBank
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[中台]-分页列表查询银行账户", notes="普通商户基本信息[中台]-分页列表查询银行账户")
	@GetMapping(value = "/bankList")
	public Result<IPage<CaishuiBusinessBank>> queryPageBankList(CaishuiBusinessBank caishuiBusinessBank,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		QueryWrapper<CaishuiBusinessBank> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusinessBank, req.getParameterMap());
		Page<CaishuiBusinessBank> page = new Page<CaishuiBusinessBank>(pageNo, pageSize);
		IPage<CaishuiBusinessBank> pageList = caishuiBusinessBankService.page(page, queryWrapper);
		if(oConvertUtils.listIsNotEmpty(pageList.getRecords())){
			for (CaishuiBusinessBank record : pageList.getRecords()) {
				//根据账号查询服务公司设置相关信息
				BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(record.getMainAccount());
				//查询记账子单元余额
				Result result = CMBApi.querySubUnitBalance(record.getMainAccount(),record.getSubAccountId(), bankSetDTO);
				if(result.isSuccess()){
					record.setBalance(BigDecimal.valueOf(oConvertUtils.getDouble(result.getResult()+"",0.00)));
				}
			}
		}
		return Result.OK(pageList);
	}

	/**
	 *   添加银行账户
	 *
	 * @param caishuiBusinessBank
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-添加银行账户", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-添加银行账户", notes="普通商户基本信息[中台]-添加银行账户")
	@PostMapping(value = "/addBank")
	@LimitSubmit(key = "middle:business:addBank:%tId")
	public Result<String> addBank(@RequestBody CaishuiBusinessBank caishuiBusinessBank) {
		//判断当前商户下，当前服务公司的银行账户是否已存在
		long count = caishuiBusinessBankService.count(QueryGenerator.initQueryWrapper(new CaishuiBusinessBank(),null)
				.lambda().eq(CaishuiBusinessBank::getBusinessId,caishuiBusinessBank.getBusinessId())
				.eq(CaishuiBusinessBank::getServiceCompanyId,caishuiBusinessBank.getServiceCompanyId()));
		if(count > 0){
			return Result.error("银行账户已存在！");
		}

		//商户信息
		CaishuiBusiness business = iCaishuiBusinessService.getById(caishuiBusinessBank.getBusinessId());
		if(oConvertUtils.isEmpty(business)){
			return Result.error("签约商户不存在！");
		}

		//服务公司信息
		CaishuiServiceCompany serviceCompany = iCaishuiServiceCompanyService.getById(caishuiBusinessBank.getServiceCompanyId());
		if(oConvertUtils.isEmpty(serviceCompany)){
			return Result.error("服务公司不存在！");
		}

		//根据账号查询服务公司设置相关信息
		BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(serviceCompany.getBankCard());

		//记账子单元编号
		String subAccountId = GENKey.genRandomString(new Random(), "0123456789", 6);

		//新增记账子单元
		Result result = CMBApi.addBookkeepingSubUnit(serviceCompany.getBankCard(),subAccountId,caishuiBusinessBank.getAccountName(), bankSetDTO);
		if(!result.isSuccess()){
			return Result.error(result.getMessage());
		}

		//设置记账子单元关联付款方信息
		Result result_rp = CMBApi.setSubUnitRelatedPayer(serviceCompany.getBankCard(),serviceCompany.getBranchCode(),
				subAccountId,business.getBankAccount(),business.getName(),bankSetDTO);
		if(!result_rp.isSuccess()){
			return Result.error(result_rp.getMessage());
		}

		caishuiBusinessBank.setSubAccountId(subAccountId);//记账子单元编号
		caishuiBusinessBank.setAccountName(caishuiBusinessBank.getAccountName());//户名
		caishuiBusinessBank.setMainAccount(serviceCompany.getBankCard());//主账号（服务公司账号）
		caishuiBusinessBank.setAccount(serviceCompany.getBankCard() + subAccountId);//打款账户（15位主账户+子单元）
		caishuiBusinessBank.setBankName(serviceCompany.getBankName());//打款开户行
		caishuiBusinessBank.setName(serviceCompany.getBankAccount());//打款户名
		caishuiBusinessBank.setTaxRate(new BigDecimal(caishuiBusinessBank.getTaxRate()).divide(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
		caishuiBusinessBank.setTaxRateTwo(new BigDecimal(caishuiBusinessBank.getTaxRateTwo()).divide(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
		caishuiBusinessBankService.save(caishuiBusinessBank);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑银行账户（设置税率）
	 *
	 * @param caishuiBusinessBank
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-编辑银行账户（设置税率）", dataType = 2, terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-编辑银行账户（设置税率）", notes="普通商户基本信息[中台]-编辑银行账户（设置税率）")
	@RequestMapping(value = "/editBank", method = {RequestMethod.PUT,RequestMethod.POST})
	@LimitSubmit(key = "middle:business:editBank:%tId", spelKey = "#caishuiBusinessBank.id")
	public Result<String> editBank(@RequestBody CaishuiBusinessBank caishuiBusinessBank) {
		caishuiBusinessBank.setTaxRate(new BigDecimal(caishuiBusinessBank.getTaxRate()).divide(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
		caishuiBusinessBank.setTaxRateTwo(new BigDecimal(caishuiBusinessBank.getTaxRateTwo()).divide(new BigDecimal(100)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue());
		caishuiBusinessBankService.updateById(caishuiBusinessBank);
		return Result.OK("设置成功!");
	}

	/**
	 * 银行关联付款白名单列表接口
	 * @param serviceCompanyId
	 * @param subAccountId
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[中台]-银行关联付款白名单列表接口", notes="普通商户基本信息[中台]-银行关联付款白名单列表接口")
	@GetMapping(value = "/whiteList")
	public Result<?> queryWhiteList(@RequestParam(name="serviceCompanyId", required = true) String serviceCompanyId,
									@RequestParam(name="subAccountId", required = true) String subAccountId) {
		//服务公司
		CaishuiServiceCompany company = iCaishuiServiceCompanyService.getById(serviceCompanyId);
		if (oConvertUtils.isEmpty(company)) return Result.error("服务公司不存在！");
		//根据账号查询服务公司设置相关信息
		BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(company.getBankCard());
		Result result = CMBApi.querySubUnitRelatedPayer(company.getBankCard(),company.getBranchCode(),subAccountId,bankSetDTO);
		if(result.isSuccess() && oConvertUtils.isNotEmpty(result.getResult())){
			JsonArray jsonArray = new GsonBuilder().create().fromJson(result.getResult().toString(), JsonArray.class);
			List<Map<String,Object>> list = new ArrayList<>();
			for (JsonElement jsonElement : jsonArray) {
				Map<String,Object> map = new HashMap<>();
				map.put("dmanam",jsonElement.getAsJsonObject().get("dmanam").getAsString());
				map.put("rltacc",jsonElement.getAsJsonObject().get("rltacc").getAsString());
				map.put("stscod",jsonElement.getAsJsonObject().get("stscod").getAsString());
				map.put("tlyopr",jsonElement.getAsJsonObject().get("tlyopr").getAsString());
				list.add(map);
			}
			return Result.OK(list);
		}else {
			return Result.ok(null);
		}
	}

	/**
	 * 设置银行账户付款白名单
	 * @param jsonObject
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-设置银行账户付款白名单", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-设置银行账户付款白名单", notes="普通商户基本信息[中台]-设置银行账户付款白名单")
	@PostMapping(value = "/addWhiteList")
	@LimitSubmit(key = "middle:business:addWhiteList:%tId")
	public Result<String> addWhiteList(@RequestBody JSONObject jsonObject) {
		String serviceCompanyId = jsonObject.getString("serviceCompanyId");//服务公司ID
		String subAccountId = jsonObject.getString("subAccountId");//记账子单元编号
		String payName = jsonObject.getString("payName");//付款账户
		String payAccount = jsonObject.getString("payAccount");//付款账号
		if (oConvertUtils.isEmpty(serviceCompanyId) || oConvertUtils.isEmpty(subAccountId)
			|| oConvertUtils.isEmpty(payName) || oConvertUtils.isEmpty(payAccount)) {
			return Result.error("参数错误！");
		}
		//服务公司
		CaishuiServiceCompany company = iCaishuiServiceCompanyService.getById(serviceCompanyId);
		if (oConvertUtils.isEmpty(company)) return Result.error("服务公司不存在！");
		//根据账号查询服务公司设置相关信息
		BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(company.getBankCard());
		Result result = CMBApi.setSubUnitRelatedPayer(company.getBankCard(),company.getBranchCode(),subAccountId,payAccount,payName,bankSetDTO);
		if(result.isSuccess()){
			return Result.OK(result.getMessage());
		}else {
			return Result.error(result.getMessage());
		}
	}

	/**
	 * 删除银行账户付款白名单
	 * @param jsonObject
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-删除银行账户付款白名单", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-删除银行账户付款白名单", notes="普通商户基本信息[中台]-删除银行账户付款白名单")
	@PostMapping(value = "/delWhiteList")
	@LimitSubmit(key = "middle:business:delWhiteList:%tId")
	public Result<String> delWhiteList(@RequestBody JSONObject jsonObject) {
		String serviceCompanyId = jsonObject.getString("serviceCompanyId");//服务公司ID
		String subAccountId = jsonObject.getString("subAccountId");//记账子单元编号
		String payName = jsonObject.getString("payName");//付款账户
		String payAccount = jsonObject.getString("payAccount");//付款账号
		if (oConvertUtils.isEmpty(serviceCompanyId) || oConvertUtils.isEmpty(subAccountId)
				|| oConvertUtils.isEmpty(payName) || oConvertUtils.isEmpty(payAccount)) {
			return Result.error("参数错误！");
		}
		//服务公司
		CaishuiServiceCompany company = iCaishuiServiceCompanyService.getById(serviceCompanyId);
		if (oConvertUtils.isEmpty(company)) return Result.error("服务公司不存在！");
		//根据账号查询服务公司设置相关信息
		BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(company.getBankCard());
		Result result = CMBApi.delSubUnitRelatedPayer(company.getBankCard(),company.getBranchCode(),subAccountId,payAccount,payName,bankSetDTO);
		if(result.isSuccess()){
			return Result.OK(result.getMessage());
		}else {
			return Result.error(result.getMessage());
		}
	}
    //========================================普通商户银行账户=========================================

	//========================================普通商户用户信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusinessUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息-分页列表查询用户信息", notes="普通商户基本信息-分页列表查询用户信息")
	@GetMapping(value = "/userList")
	public Result<IPage<CaishuiBusinessUser>> queryPageUserList(CaishuiBusinessUser caishuiBusinessUser,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		QueryWrapper<CaishuiBusinessUser> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusinessUser, req.getParameterMap());
		Page<CaishuiBusinessUser> page = new Page<CaishuiBusinessUser>(pageNo, pageSize);
		IPage<CaishuiBusinessUser> pageList = caishuiBusinessUserService.pageMultiTable(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param caishuiBusinessUser
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-添加用户信息", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-添加用户信息", notes="普通商户基本信息[中台]-添加用户信息")
	@PostMapping(value = "/addUser")
	@LimitSubmit(key = "middle:business:addUser:%tId")
	public Result<?> addUser(@RequestBody CaishuiBusinessUser caishuiBusinessUser) {
		return caishuiBusinessUserService.addBusinessUser(caishuiBusinessUser);
	}

	/**
	 *  编辑
	 *
	 * @param caishuiBusinessUser
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-编辑用户信息",dataType = 2, terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-编辑用户信息", notes="普通商户基本信息[中台]-编辑用户信息")
	@RequestMapping(value = "/editUser", method = {RequestMethod.PUT,RequestMethod.POST})
	@LimitSubmit(key = "middle:business:editUser:%tId", spelKey = "#caishuiBusinessUser.id")
	public Result<?> editUser(@RequestBody CaishuiBusinessUser caishuiBusinessUser) {
		return caishuiBusinessUserService.editBusinessUser(caishuiBusinessUser);
	}

	/**
	 *   通过id删除商户用户
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[中台]-通过id删除商户用户", terminal = 1)
	@ApiOperation(value="普通商户基本信息[中台]-通过id删除商户用户", notes="普通商户基本信息[中台]-通过id删除商户用户")
	@DeleteMapping(value = "/deleteUser")
	@LimitSubmit(key = "middle:business:deleteUser:%tId", spelKey = "#id")
	public Result<?> deleteUser(@RequestParam(name="id",required=true) String id) {
		return caishuiBusinessUserService.deleteBusinessUser(id);
	}
	//========================================普通商户用户信息=========================================

	//========================================渠道商户基本信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusiness
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="渠道商户基本信息[中台]-分页列表查询", notes="渠道商户基本信息[中台]-分页列表查询")
	@GetMapping(value = "/channelList")
	public Result<IPage<CaishuiBusiness>> queryPageChannelList(CaishuiBusiness caishuiBusiness,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																HttpServletRequest req) {
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
		queryWrapper.lambda().eq(CaishuiBusiness::getType,3);//渠道商户
		Page<CaishuiBusiness> page = new Page<CaishuiBusiness>(pageNo, pageSize);
		IPage<CaishuiBusiness> pageList = iCaishuiBusinessService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-添加", terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-添加", notes="渠道商户基本信息[中台]-添加")
	@PostMapping(value = "/addChannel")
	@LimitSubmit(key = "middle:business:addChannel:%tId")
	public Result<String> addChannel(@RequestBody CaishuiBusiness caishuiBusiness) {
		LoginUser loginUser = TokenUtils.getLoginUser();
		caishuiBusiness.setType(3);
		caishuiBusiness.setCreateBy(loginUser.getRealname());
		caishuiBusiness.setUserId(loginUser.getId());
		double taxRate = 0.00;
		try {
			taxRate = Double.parseDouble(caishuiBusiness.getTaxRate() + "");
			if(taxRate <= 0 || taxRate > 50){
				return Result.error("税率必须大于0且小于等于50！");
			}
			caishuiBusiness.setTaxRate(new BigDecimal(caishuiBusiness.getTaxRate()).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
			iCaishuiBusinessService.save(caishuiBusiness);
		}catch (Exception e){
			return Result.error("添加失败！");
		}
		return Result.OK("添加成功！",caishuiBusiness.getId());
	}

	/**
	 *  编辑
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-编辑", dataType = 2, terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-编辑", notes="渠道商户基本信息[中台]-编辑")
	@RequestMapping(value = "/editChannel", method = {RequestMethod.PUT,RequestMethod.POST})
	@LimitSubmit(key = "middle:business:editChannel:%tId", spelKey = "#caishuiBusiness.id")
	public Result<String> editChannel(@RequestBody CaishuiBusiness caishuiBusiness) {
		//当前登录用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		caishuiBusiness.setUpdateBy(loginUser.getRealname());
		caishuiBusiness.setTaxRate(new BigDecimal(caishuiBusiness.getTaxRate()).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
		iCaishuiBusinessService.updateById(caishuiBusiness);
		return Result.OK("编辑成功!",caishuiBusiness.getId());
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-通过id删除", terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-通过id删除", notes="渠道商户基本信息[中台]-通过id删除")
	@DeleteMapping(value = "/deleteChannel")
	@LimitSubmit(key = "middle:business:deleteChannel:%tId", spelKey = "#id")
	public Result<String> deleteChannel(@RequestParam(name="id",required=true) String id) {
		iCaishuiBusinessService.removeById(id);
		return Result.OK("删除成功!");
	}

	//========================================渠道商户基本信息=========================================

	//========================================渠道商户用户信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiMiddleUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="渠道商户基本信息[中台]-分页列表查询用户信息", notes="渠道商户基本信息[中台]-分页列表查询用户信息")
	@GetMapping(value = "/userListChannel")
	public Result<IPage<CaishuiMiddleUser>> queryPageUserListChannel(CaishuiMiddleUser caishuiMiddleUser,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																HttpServletRequest req) {
		QueryWrapper<CaishuiMiddleUser> queryWrapper = QueryGenerator.initQueryWrapper(caishuiMiddleUser, req.getParameterMap());
		Page<CaishuiMiddleUser> page = new Page<CaishuiMiddleUser>(pageNo, pageSize);
		IPage<CaishuiMiddleUser> pageList = iCaishuiMiddleUserService.pageMultiTable(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param caishuiMiddleUser
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-添加用户信息", terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-添加用户信息", notes="渠道商户基本信息[中台]-添加用户信息")
	@PostMapping(value = "/addUserChannel")
	@LimitSubmit(key = "middle:business:addUserChannel:%tId")
	public Result<?> addUserChannel(@RequestBody CaishuiMiddleUser caishuiMiddleUser) {
		return iCaishuiMiddleUserService.addMiddleUser(caishuiMiddleUser);
	}

	/**
	 *  编辑
	 *
	 * @param caishuiMiddleUser
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-编辑用户信息",dataType = 2, terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-编辑用户信息", notes="渠道商户基本信息[中台]-编辑用户信息")
	@RequestMapping(value = "/editUserChannel", method = {RequestMethod.PUT,RequestMethod.POST})
	@LimitSubmit(key = "middle:business:editUserChannel:%tId", spelKey = "#caishuiMiddleUser.id")
	public Result<?> editUserChannel(@RequestBody CaishuiMiddleUser caishuiMiddleUser) {
		return iCaishuiMiddleUserService.editMiddleUser(caishuiMiddleUser);
	}

	/**
	 *   通过id删除商户用户
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "渠道商户基本信息[中台]-通过id删除商户用户", terminal = 1)
	@ApiOperation(value="渠道商户基本信息[中台]-通过id删除商户用户", notes="渠道商户基本信息[中台]-通过id删除商户用户")
	@DeleteMapping(value = "/deleteUserChannel")
	@LimitSubmit(key = "middle:business:deleteUserChannel:%tId", spelKey = "#id")
	public Result<?> deleteUserChannel(@RequestParam(name="id",required=true) String id) {
		return iCaishuiMiddleUserService.deleteMiddleUser(id);
	}
	//========================================渠道商户用户信息=========================================

	/**
	 * 根据绑定商户ID查询公司绑定数据
	 * @param businessIds
	 * @return
	 */
	@GetMapping("/queryBusinessByIds")
	public Result<?> queryBusinessByIds(@RequestParam(name="businessIds",required=false) String businessIds) {
		//查询未绑定的普通商户
		List<CaishuiBusiness> businessList = iCaishuiBusinessService.list(new LambdaQueryWrapper<CaishuiBusiness>()
				.select(CaishuiBusiness::getId,CaishuiBusiness::getName)
				.eq(CaishuiBusiness::getType,1).eq(CaishuiBusiness::getIsDefault,0)
				.isNull(CaishuiBusiness::getChannelBusinessId));
		//查询已绑定当前数据的普通商户
		if (oConvertUtils.isNotEmpty(businessIds)){
			List<CaishuiBusiness> businessList1 = iCaishuiBusinessService.list(new LambdaQueryWrapper<CaishuiBusiness>()
					.select(CaishuiBusiness::getId,CaishuiBusiness::getName).in(CaishuiBusiness::getId, businessIds));
			businessList.addAll(businessList1);
		}
		return Result.ok(businessList);
	}

}
